package gps.monitor.jt809server.network.netty;

import gps.monitor.jt809server.entity.DownPlatformAccount;
import gps.monitor.jt809server.protocol.model.AbstractJt809Message;
import gps.monitor.jt809server.protocol.codec.IJt809Handler;
import gps.monitor.jt809server.protocol.Jt809ParseException;
import gps.monitor.jt809server.protocol.Jt809ProtocolFactory;
import gps.monitor.jt809server.service.LinkStatusService;
import gps.monitor.jt809server.util.ProtocolUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 对每一条协议进行解析
 *
 * @author cyq
 * @date 2021/11/5
 * @desc talk is cheep,show me the code
 */
public class SimpleJt809NettyHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private LinkStatusService linkStatusService;

    //5B0000005A020047E022120004C4C3A10000010000000000D0C24E4531523738000000000000000000000000000112020000002400040B07E50C3A0B04C1F7710237D341000000000000000100B10000000000020000000083425D
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            ByteBuf data = (ByteBuf) msg;
            //去除转义
            ByteBuf deEscapeBuf = ProtocolUtils.deEscape(data);
            String msgId = ByteBufUtil.hexDump(deEscapeBuf, 9, 2);
            int centerId = Integer.valueOf(ByteBufUtil.hexDump(deEscapeBuf, 11, 4), 16);
            DownPlatformAccount downPlatformAccount = linkStatusService.getDownPlatformInfo(centerId);
            if (downPlatformAccount == null) {
                //data.release();
                return;
            }
            IJt809Handler handler = Jt809ProtocolFactory.getJt809Handler(msgId);
            if (handler == null) {
                //data.release();
                return;
            }
            try {
                AbstractJt809Message message = handler.read(deEscapeBuf, downPlatformAccount);
            } catch (Jt809ParseException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
